package com.shaonian.search.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shaonian.search.model.dto.post.PostQueryRequest;
import com.shaonian.search.model.entity.Post;
import com.shaonian.search.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author 少年
 */
@Slf4j
//@Component
public class FetchInitPostList implements CommandLineRunner {

    @Resource
    private PostService postService;

//    @Override
//    public void run(String... args) throws Exception {
//        String json = "{\"current\":1,\"pageSize\":8,\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"category\":\"文章\",\"reviewStatus\":1}\n";
//        String url = "https://www.code-nav.cn/api/post/search/page/vo";
//
//        String body = HttpRequest.post(url)
//                .body(json)
//                .execute()
//                .body();
//        Map<String, Object> map = JSONUtil.toBean(body, Map.class);
//        System.out.println(map);
//        JSONObject data = (JSONObject) map.get("data");
//        JSONArray records = (JSONArray) data.get("records");
//        List<Post> postList = new ArrayList<>();
//        for (Object recode : records) {
//            Post post = new Post();
//            JSONObject tempRecode = (JSONObject) recode;
//            post.setTitle(tempRecode.getStr("title"));
//            post.setContent(tempRecode.getStr("content"));
//            JSONArray tags = tempRecode.getJSONArray("tags");
//            List<String> tagsList = tags.toList(String.class);
//            post.setTags(JSONUtil.toJsonStr(tagsList));
//            post.setUserId(1657380878698496002L);
//            postList.add(post);
//        }
//        //数据入库
//        boolean b = postService.saveBatch(postList);
//        if (b) {
//            log.info("获取初始化帖子列表成功，条数 = {}", postList.size());
//        } else {
//            log.error("获取初始化帖子列表失败");
//        }
//    }


    @Override
    public void run(String... args) throws Exception {
        //构造请求与请求参数
        String json = "{\"current\":1,\"pageSize\":8,\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"category\":\"文章\",\"tags\":[],\"reviewStatus\":1}";
        String url = "https://www.code-nav.cn/api/post/search/page/vo";
        //发送请求，获取编程导航这个网站的文章数据
        String result = HttpRequest.post(url).body(json).execute().body();
        if (result == null){
            throw new RuntimeException("帖子接口请求失败");
        }

        //解析数据
        Map<String,Object> map = JSONUtil.toBean(result, Map.class);
        if (Integer.parseInt(map.get("code").toString()) != 0){
            throw new RuntimeException("数据解析异常");
        }
        JSONObject data = (JSONObject) map.get("data");
        if (data == null){
            throw new RuntimeException("数据解析异常");
        }
        JSONArray records = (JSONArray) data.get("records");
        if (records == null){
            throw new RuntimeException("数据解析异常");
        }

        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
            JSONObject tempRecord = (JSONObject) record;
            Post post = new Post();
            post.setTitle(tempRecord.getStr("title"));
            post.setContent(tempRecord.getStr("content"));

            //获取文章标签:
            JSONArray tags = (JSONArray) tempRecord.get("tags");
            String tagJson = JSONUtil.toJsonStr(tags);
            post.setTags(tagJson);
            //管理员用户id
            post.setUserId(1764584057896873986L);
            Post isInsert = getIsInsert(tempRecord.getStr("title"));
            if (isInsert == null){
                //当数据库不存在这个数据时，才选择进行插入
                postList.add(post);
            }
        }
        //插入到我们的数据库当中（帖子表）
        boolean saveBatch = postService.saveBatch(postList);
        if (!saveBatch){
            throw new RuntimeException("数据保存失败");
        }
        log.info("帖子列表数据已初始化成功，条数：",postList.size());
    }



    private Post getIsInsert(String title) {
        PostQueryRequest postQueryRequest = new PostQueryRequest();
        postQueryRequest.setTitle(title);
        QueryWrapper<Post> queryWrapper = postService.getQueryWrapper(postQueryRequest);
        Post isInsert = postService.getOne(queryWrapper);
        return isInsert;
    }
}
